package com.example.demo20230927;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/add")
    public ResponseEntity<String> addUser(@RequestBody User user) {
        // 检查用户名是否重复
        User existingUser = userMapper.findUserByUsername(user.getUsername());
        if (existingUser != null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名已存在，请选择其他用户名");
        }

        // 如果用户名不重复，则进行用户添加
        userService.addUser(user);
        return ResponseEntity.ok("用户添加成功");
    }
    @GetMapping("/checkDuplicateUsername/{username}")
    public boolean checkDuplicateUsername(@PathVariable String username) {
        // 检查用户名是否存在
        User existingUser = userMapper.findUserByUsername(username);
        return existingUser != null;
    }


    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User loginUser) {
        Map<String, Object> result = new HashMap<>();
        boolean success = userService.loginUser(loginUser.getUsername(), loginUser.getPassword());

        if (success) {
            String token = JwtUtil.generateToken(loginUser.getUsername());
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("token", token);
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }

        return result;
    }

    @GetMapping("/info")
    public ResponseEntity<?> getUserInfo(@RequestHeader("Authorization") String token) {
        try {
            User userInfo = userService.getUserInfoByToken(token);
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }
}
